<!--
 * @Author: XieQiu 雪球
 * @Date: 2021-05-10 15:07:25
 * @LastEditTime: 2023-07-10 11:20:55
 * @LastEditors: Please set LastEditors
 * @Description: 巡检线路管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="79"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="88%"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="inspectionRouteName" label="巡查线路名称" />
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.inspectionRouteId" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="dbHandleEdit(scope.row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
            <el-button
              v-if="judgePermission(79, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(79, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>

    <template v-slot:dialog>
      <el-dialog
        :title="titleText + '巡查线路信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            label="巡查线路名称:"
            prop="inspectionRouteName"
            class="w100p"
          >
            <el-input
              v-model="formData.inspectionRouteName"
              placeholder="请输入巡查线路名称"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="巡查点:"
            prop="routePointMapperList"
            class="w100p pointList"
          >
            <div class="df">
              <el-select
                v-model="nowPointId"
                filterable
                clearable
                @change="changenowPointId"
              >
                <el-option
                  v-for="item in allPointList"
                  :key="item.inspectionPointId"
                  :label="item.inspectionPointName"
                  :value="item.inspectionPointId"
                />
              </el-select>
              <i class="el-icon-circle-plus-outline" @click="addPoint"></i>
            </div>
            <div class="tags">
              <div
                v-for="item in tagsList"
                :key="item.inspectionPointId"
                class="tag-item"
              >
                <div class="point-name">{{ item.inspectionPointName }}</div>
                <div class="close">
                  <i
                    class="el-icon-circle-close"
                    @click="removeTheTag(item.inspectionPointId)"
                  ></i>
                </div>
              </div>
            </div>
          </el-form-item>
          <baidu-map
            class="map"
            style="height: 68%; width: 96%;"
            :center="center"
            :zoom="zoom"
            :scroll-wheel-zoom="true"
            map-type="BMAP_HYBRID_MAP"
          >
            <!-- @click="setCenterPoint" -->
            <bm-marker
              v-for="(item, index) in tagsList"
              :key="index"
              :position="{ lng: item.longitude, lat: item.latitude }"
              :dragging="false"
              animation="BMAP_ANIMATION_BOUNCE"
              :title="item.inspectionPointName"
              @click="lookDetail(item)"
            >
              <bm-label
                :content="item.inspectionPointName"
                :label-style="labelStyle"
                :offset="{width: -15, height: 30}"
              />
            </bm-marker>
            <bm-polyline
              stroke-style="dashed"
              stroke-color="#6ecae3"
              :stroke-opacity="1"
              :stroke-weight="4"
              :path="tagsList"
            />
            <bm-control>
              <bm-auto-complete
                v-model="keyword"
                :sug-style="{ zIndex: 999999 }"
              >
                <el-input
                  v-model="keyword"
                  type="text"
                  placeholder="请输入地名关键字"
                  style="background-color:#003947;"
                  clearable
                >
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </bm-auto-complete>
            </bm-control>
            <bm-local-search
              :keyword="keyword"
              :auto-viewport="true"
              :panel="false"
            />
          </baidu-map>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="'巡检线路信息'" :visible.sync="dialogNoticeFormVisible">
        <baidu-map
          class="map"
          style="height: 100%; width: 96%;"
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          map-type="BMAP_HYBRID_MAP"
        >
          <!-- @click="setCenterPoint" -->
          <bm-marker
            v-for="(item, index) in polylinePath"
            :key="index"
            :position="{ lng: item.lng, lat: item.lat }"
            :dragging="false"
            animation="BMAP_ANIMATION_BOUNCE"
            :title="item.title.inspectionPointName"
            @click="lookDetail(item)"
          >
            <bm-label
              :content="item.title.inspectionPointName"
              :label-style="labelStyle"
              :offset="{width: -15, height: 30}"
            />
          </bm-marker>
          <bm-polyline
            stroke-style="dashed"
            stroke-color="#6ecae3"
            :stroke-opacity="1"
            :stroke-weight="4"
            :path="polylinePath"
          />
          <bm-control>
            <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
              <el-input
                v-model="keyword"
                type="text"
                placeholder="请输入地名关键字"
                style="background-color:#003947;"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </bm-auto-complete>
          </bm-control>
          <bm-local-search
            :keyword="keyword"
            :auto-viewport="true"
            :panel="false"
          />
        </baidu-map>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import patrolInfoManage from "@/api/digital-operation/patrol-info-manage/patrol-line-manage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
export default {
  name: "PatrolLineManage",
  components: {
    SearchForm,
    ActionBar,
    Pagination,
    BaseMainSlot,
  },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '巡查线路名称',
          prop: 'routeName',
          type: 'input',
        },
      ],
      searchlist: {},
      obj: {
        name: ""
      },
      // 巡检点名称
      routeName: "",
      // 是否能输入
      canInput: false,
      // 选中的数据项数组 ID组成
      inspectionRouteIdList: [],
      // 所有巡查点的列表
      allPointList: [],
      // 当前选中的巡查点ID
      nowPointId: "",
      // tag列表
      tagsList: [],
      // 选中的数据项数组 ID组成
      inspectionPointIdList: [],
      // 地图相关值
      // center: { lng: 120.065772, lat: 30.89475 },
      center: { lng: 120.230648, lat: 30.811543 },
      polylinePath: [],
      start: {},
      end: {},
      // zoom: 15,
      zoom: 18,
      keyword: "",
      show: false,
      position: {},
      labelStyle: {
        color: "#fffff0",
        fontSize: "12px",
        borderRadius: "8px",
        border: "none",
        backgroundColor: "#00a1c2",
        padding: "3px",
        opacity: ".8"
      },
      rules: {
        inspectionRouteName: [
          { required: true, message: "请输入巡查线路名称", trigger: "blur" }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false,
      dialogNoticeFormVisible: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // 获取巡查点列表
    this.getPointList();
  },
  mounted() {
    let that = this;
    that.getdatatime();
    // 获取表格数据
    this.getTableDataList();
  },
  methods: {
    // updatePolylinePath (e) {
    //   // console.log(e)
    //   this.polylinePath = e.target.getPath()
    // },
    // addPolylinePoint () {
    //   this.polylinePath.push({ lng: 120.230648, lat: 30.811543 })
    // },
    getTableDataList() {
      this.allPointList = [];
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          inspectionRouteName: this.searchlist.routeName,
          organizationNo: sessionStorage.organizationNo
        }
      };
      patrolInfoManage.getInspectionRouteList(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.tagsList = [];
          this.getPointList();
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    infoWindowClose() {
      this.show = false;
    },
    infoWindowOpen() {
      this.show = true;
    },
    getPointList() {
      patrolInfoManage.getInspectionPointCondition().then(res => {
        this.allPointList = res.data;
        // console.log(this.allPointList)
      });
    },
    changenowPointId(val) {
      this.nowPointId = val;
    },
    // 增加巡检点 tagsList => [{inspectionPointId: 1, inspectionPointName: '1'}] formData.routePointMapperList => tagsList
    addPoint() {
      // if (!this.canInput) {
      //   return;
      // } else {
      // 新增点的对象数据数组
      let arr = this.allPointList.filter(
        item => item.inspectionPointId === this.nowPointId
      );
      // 判断是否存在该巡查点 inspectionPointId组成新数组
      let idList = this.tagsList.map(item => item.inspectionPointId);
      if (idList.includes(arr[0].inspectionPointId)) {
        this.$message.warning("该巡查点已经存在~");
        return;
      } else {
        this.tagsList = JSON.parse(JSON.stringify(this.tagsList.concat(arr)));
        // console.log(this.tagsList);
      }
      // }
    },
    removeTheTag(pointId) {
      // if (this.canInput) {
      this.tagsList.forEach((item, index) => {
        if (item.inspectionPointId === pointId) {
          this.tagsList.splice(index, 1);
        }
      });
      // } else {
      //   this.$message.warning("点击修改按钮后可删除~");
      // }
    },
    // // 点击地图
    // setCenterPoint({ type, target, point, pixel, overlay }) {
    //   this.center.lng = point.lng;
    //   this.center.lat = point.lat;
    //   this.formData.longitude = point.lng;
    //   this.formData.latitude = point.lat;
    // },
    getdatatime() {
      // 默认显示今天
      this.formData.warehousingTime = new Date();
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // add(){
    //   this.formData={};
    //   this.openDialog('add')
    // },
    handleEdit(row) {
      // TODO 点击行元素后 edit
      if (!row.inspectionRouteId) return;
      this.formData = JSON.parse(JSON.stringify(row));
      // console.log(row)

      this.nowPointId = "";
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      // this.$refs.formData.resetFields();
      this.canInput = true;
      // this.openDialog('edit')
    },

    dbHandleEdit(row) {
      if (!row.inspectionRouteId) return;
      this.getDetailInspectionRouteById(row.inspectionRouteId);
      setTimeout(() => {
        // console.log(this.polylinePath[0])
        if (this.polylinePath[0]) {
          // this.center = this.polylinePath[0]
          if (this.polylinePath.length > 0) {
            var maxLng = this.polylinePath[0].lng;
            var minLng = this.polylinePath[0].lng;
            var maxLat = this.polylinePath[0].lat;
            var minLat = this.polylinePath[0].lat;
            var res;
            for (var i = this.polylinePath.length - 1; i >= 0; i--) {
              res = this.polylinePath[i];
              if (res.lng > maxLng) maxLng = res.lng;
              if (res.lng < minLng) minLng = res.lng;
              if (res.lat > maxLat) maxLat = res.lat;
              if (res.lat < minLat) minLat = res.lat;
            }
            this.center.lng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
            this.center.lat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;
          }
          this.zoom = 17;
        }
      }, 600);
      this.dialogNoticeFormVisible = true;
    },
    cancel() {
      this.nowChanceStau = "";
      this.nowPointId = "";
      this.tagsList = [];
      this.formData = {};
      this.zoom = 18;
      this.polylinePath = [];
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      this.closeDialog("edit");
    },
    // 获取该路线的详细数据
    getDetailInspectionRouteById(id) {
      this.polylinePath = [];
      patrolInfoManage.getDetailInspectionRouteById(id).then(res => {
        this.tagsList = res.data.inspectionPointList;
        // console.log(this.tagsList);
        if (this.tagsList) {
          this.tagsList.forEach(item => {
            // console.log(item)
            let obj = {};
            obj["lat"] = item.latitude;
            obj["lng"] = item.longitude;
            obj["title"] = item;
            this.polylinePath.push(obj);
          });
        }
      });
    },
    lookDetail(items) {
      // console.log(items)
      this.position = items;
      this.show = true;
    },
    handleSelectionChange(list) {
      this.inspectionRouteIdList = [];
      this.inspectionRouteIdList = list.map(item => item.inspectionRouteId);
      if (this.inspectionRouteIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage(formData) {
      patrolInfoManage
        .delInspectionRouteInfo(this.inspectionRouteIdList)
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            // this.$refs[formData].resetFields();/**/
            this.getTableDataList();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(data) {
      // patrolInfoManage
      //   .delInspectionRouteInfo([data.inspectionRouteId])
      //   .then(res => {
      //     if (res.code === 1) {
      //       this.$message.success(res.msg);
      //       // this.$refs[formData].resetFields();
      //       this.getTableDataList();
      //     } else {
      //       this.$message.warning(res.msg || '删除失败');
      //     }
      //   });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          patrolInfoManage
            .delInspectionRouteInfo([data.inspectionRouteId])
            .then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.getTableDataList();
              } else {
                this.$message.warning(res.msg || "删除失败");
              }
            });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          this.polygonPath = [];
          this.tagsList.forEach(item => {
            // console.log(item);
            // console.log(this.inspectionPointId);
            this.inspectionPointId = this.$set(
              item,
              "inspectionPointId",
              item.inspectionPointId
            );
            let obj = this.inspectionPointId;
            this.polygonPath.push(obj);
          });
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // 巡检点数组赋值进formData
            this.formData.inspectionPointIdList = this.polygonPath;
            patrolInfoManage
              .editInspectionRouteInfo(this.formData)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg || "修改成功！");
                  this.closeDialog();
                  this.getPointList();
                  this.nowPointId = "";
                  this.polylinePath = [];
                  this.$refs[formData].resetFields();
                  this.getTableDataList();
                } else {
                  this.$message.error(res.msg || "修改失败！");
                }
              });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            this.formData.inspectionPointIdList = this.polygonPath;
            patrolInfoManage.addInspectionRouteInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.closeDialog();
                this.getPointList();
                this.nowPointId = "";
                this.tagsList = [];
                this.polylinePath = [];
                this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep .content {
  .table-box {
    width: 50% !important;
  }
  .form {
    width: 48% !important;
  }
}
::v-deep .el-form-item__label {
  text-align: end;
  min-width: 120px !important;
}
.pointList {
  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
  .noClick {
    cursor: not-allowed;
  }
  .df {
    display: flex;
    align-items: center;
    width: 100%;
  }
  ::v-deep .el-form-item__content {
    flex-direction: column;
  }
  .label {
    min-width: 120px !important;
  }
  .tags {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .tag-item {
      height: 30px;
      padding: 5px 10px;
      background-color: #00a1c2;
      border-radius: 8px;
      display: flex;
      align-items: center;
      margin-top: 10px;
      margin-right: 10px;
      i {
        font-size: 14px;
      }
    }
  }
}
::v-deep .form {
  position: relative;
}
.map {
  position: absolute;
  bottom: 0px;
  width: 100%;
  height: 100%;
}
.lng {
  ::v-deep .el-input__inner {
    min-width: 70px;
  }
}
.lat {
  ::v-deep .el-form-item__label {
    text-align: end;
    min-width: 100px !important;
  }
}
::v-deep .BMap_pop {
  left: 102px !important;
}
/*地图标题*/
::v-deep .BMap_bubble_title {
  // color:white;
  font-size: 13px;
  font-weight: bold;
  text-align: left;
  padding-left: 5px;
  padding-top: 5px;
  width: 10px;
  // border-bottom:1px solid gray;
  // background-color:#0066b3;
}
/* 消息内容 */
::v-deep .BMap_bubble_content {
  background-color: white;
  padding-left: 5px;
  padding-top: 5px;
  padding-bottom: 10px;
}
/* 内容 */
::v-deep .BMap_pop div:nth-child(9) {
  top: 35px !important;
  border-radius: 7px;
}
/* 左上角删除按键 */
::v-deep .BMap_pop img {
  top: 40px !important;
  left: 5555px !important;
}
::v-deep .BMap_top {
  display: none;
}
::v-deep .BMap_bottom {
  display: none;
}
::v-deep .BMap_center {
  display: none;
}
/* 隐藏边角 */
::v-deep .BMap_pop div:nth-child(1) div {
  display: none;
}
::v-deep .BMap_pop div:nth-child(4) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(3) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(5) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(6) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(7) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(8) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(9) {
  box-sizing: content-box;
  width: 110px !important;
  /* height: 55px; */
  position: absolute;
  left: 16px;
  top: 16px;
  z-index: 10;
  overflow: hidden;
}
::v-deep .BMap_shadow {
  display: none;
}
::v-deep .el-dialog__wrapper {
  .el-dialog {
    height: 78vh;
    margin-top: 0vh !important;

    .el-dialog__body {
      overflow: hidden;
      position: relative;
      height: 90%;
    }
  }
}
::v-deep .dialog {
  .el-dialog__headerbtn {
    top: 0;
    right: 10px;
  }
  .el-dialog {
    min-width: 15%;
    width: 200px !important;
    height: auto !important;
  }
}
</style>
